import React, { useState } from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input, Tabs, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../stores/authStore';
import { login } from '../request/login';
import { LoginResponse } from '../types/login';
import styles from './Login.module.css';

const Login: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const { login: setAuth } = useAuthStore();

  const onFinish = async (values: any) => {
    setLoading(true);
    try {
      // Call the actual login API
      const response: LoginResponse = await login(values.username, values.password);
      
      if (response.code === '0000') {
        message.success('登录成功！');
        
        // Store token in localStorage
        localStorage.setItem('token', response.data.accessToken);
        
        // Set authentication state using Zustand
        setAuth({
          username: response.data.userInfo.username,
          phone: response.data.userInfo.phone,
          nickname: response.data.userInfo.nickname,
          logo: response.data.userInfo.logo,
          email: response.data.userInfo.email,
          id: response.data.userInfo.id,
          token: response.data.accessToken,
          refreshToken: '', // New API doesn't provide refreshToken
          expireIn: response.data.expireIn
        });
        
        navigate('/workData');
        // navigate('/dashboard/analysis');
      } else {
        message.error(response.message || '登录失败，请检查用户名和密码');
      }
    } catch (error: any) {
      console.error('Login error:', error);
      message.error(error.message || '登录失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.loginForm}>
        <div className={styles.title}>
          <h1>农福车辆作业系统</h1>
          {/* <p>请登录您的账户</p> */}
        </div>
        
        <Tabs
          defaultActiveKey="account"
          items={[
            {
              key: 'account',
              label: '账户密码登录',
              children: (
                <Form
                  name="normal_login"
                  className={styles.form}
                  initialValues={{ remember: true }}
                  onFinish={onFinish}
                >
                  <Form.Item
                    name="username"
                    rules={[{ required: true, message: '请输入您的手机号!' }]}
                  >
                    <Input prefix={<UserOutlined />} placeholder="手机号" />
                  </Form.Item>
                  <Form.Item
                    name="password"
                    rules={[{ required: true, message: '请输入您的密码!' }]}
                  >
                    <Input
                      prefix={<LockOutlined />}
                      type="password"
                      placeholder="密码"
                    />
                  </Form.Item>
                  <Form.Item>
                    {/* <Form.Item name="remember" valuePropName="checked" noStyle>
                      <Checkbox>自动登录</Checkbox>
                    </Form.Item> */}

                    {/* <a className={styles.forgotPassword} href="">
                      忘记密码
                    </a> */}
                  </Form.Item>

                  <Form.Item>
                    <Button type="primary" htmlType="submit" className={styles.loginButton} loading={loading} block>
                      登录
                    </Button>
                    {/* 或 <a href="">现在注册!</a> */}
                  </Form.Item>
                </Form>
              ),
            },
          ]}
        />
      </div>
    </div>
  );
};

export default Login;